﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Threading.Tasks;
using WebServerX.Logging;

namespace WebServerX
{
    public class Client
    {
        #region Properties

        public CancellationToken CancellationToken
        {
            get { return _cancellationToken; }
        }
        private CancellationToken _cancellationToken = CancellationToken.None;

        public Server Server
        {
            get { return _server; }
        }
        private Server _server = null;

        public TcpClient TcpClient
        {
            get { return _tcpClient; }
        }
        private TcpClient _tcpClient = null;

        #endregion

        #region Public Methods

        public Client(CancellationToken cancellationToken, Server server)
        {
            this._cancellationToken = cancellationToken;
            this._server = server;

            this.Wait();
        }

        #endregion

        #region Private Methods

        private void Wait()
        {
            this._tcpClient = this.Server.Tcp.AcceptTcpClient();

            Logger.Log(String.Format("Accepted client: {0}", this.TcpClient.Client.LocalEndPoint));

            Task.Factory.StartNew(() => this.ClientMain(), this.CancellationToken);
        }

        private void ClientMain()
        {
            Request req = new Request();

            NetworkStream ns = this.TcpClient.GetStream();

            req.Get(ns);

            Response res = new Response(req);

            res.Get(ns);

            ns.Close();

            this.TcpClient.Close();
        }

        #endregion
    }
}
